package top.hkyzf.study.j2se.juc.locks;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁（递归锁）
 * synchronized ReentrantLock() 非公平锁
 * ReentrantLock(true) 公平锁
 * @author zhufeng
 * @version 1.0
 * @date 2021-3-10 22:29
 */
public class ReentrantLockDemo {

    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(() -> {
            phone.sendSMS();
        }, "AAA").start();

        new Thread(() -> {
            phone.sendSMS();
        }, "BBB").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("============================");

        Thread t1 = new Thread(phone, "CCC");
        Thread t2 = new Thread(phone, "DDD");
        t1.start();
        t2.start();
    }
}

class Phone implements Runnable {
    public synchronized void sendSMS() {
        System.out.println(Thread.currentThread().getName() + " 发送短信成功");
        sendMail();
    }

    public synchronized void sendMail() {
        System.out.println(Thread.currentThread().getName() + " 发送邮件成功");
    }

    private ReentrantLock reentrantLock = new ReentrantLock();
    @Override
    public void run() {
        reentrantLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " run invoke");
            get();
        } finally {
            reentrantLock.unlock();
        }
    }

    private void get() {
        reentrantLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " get invoke");
        } finally {
            reentrantLock.unlock();
        }
    }
}